/*
 * @Descripttion: 
 * @version: 
 * @Author: Jinjin
 * @Date: 2022-04-28 10:01:03
 * @LastEditors: Jinjin
 * @LastEditTime: 2022-05-22 15:51:28
 */
//这个文件专门用来存放关于列表的所有接口
const Router = require('koa-router')
const thumb = new Router()
const db = require('../util/db')
const bodyparser = require('koa-bodyparser')
thumb.use(bodyparser())//调用这个中间件 就可以拿到前端post过来的数据

thumb.get('/', async (ctx) => {
    ctx.body='为什么进不去吖'
})
//写对应的接口
//查询数据点赞表接口
thumb.get('/thumbs_Up', async (ctx) => {
    console.log('---------------------')
    /*     console.log(ctx.query) */
    console.log(ctx)
    console.log('我是开始status'+ctx.response.status)
    const obj = ctx.query
    var str = 'where '
    for (key in obj) {
        var name = `${key}='${obj[key]}' and `
        str += name
    }
/*     console.log(str)
    console.log(str.slice(0,-4)) */
    let searchSql = 'select * from thumbs_up '+str.slice(0,-4)
    let result= await new Promise((resolve, reject) => {
        return db.query(searchSql, (err, data) => {
            if (err) throw err;
            console.log(data)
            resolve(data)  //会扔出去一个数组
        })
    })
    if (result.length == 0) {
        ctx.body = '数据库里没有这条数据嗷~';
        ctx.response.status = 404
        console.log('我是没有数据返回时的status' + ctx.response.status)
        console.log(ctx.response)
    } else {
        ctx.response.status = 200
        ctx.body = result
        console.log(ctx.response)
    }
    console.log('---------------------')
})
//增加点赞表数据接口
thumb.post('/thumbs_Up', async (ctx) => {
    console.log(ctx.request.body)
    const obj = ctx.request.body
    var arr = Object.keys(obj);
    console.log(arr)//['type','name']
    if (arr.length != 0) {
        var keystr = ''
        var valuestr=''
        for (key in obj) {
            var keys = `${key},`
            var values=`'${obj[key]}',`
            keystr += keys
            valuestr+=values
        }
        let addSql='insert into thumbs_up('+keystr.slice(0,-1)+')values('+valuestr.slice(0,-1)+')'
         await new Promise((resolve, reject) => {
            return db.query(addSql, (err, data) => {
                if (err) throw err;
                console.log(data)
                ctx.body='插入成功'
            })
        })
    }

})
//删除点赞表数据接口
thumb.delete('/thumbs_Up', async (ctx) => {
    const obj = ctx.query
    var str = 'where '
    for (key in obj) {
        var name = `${key}='${obj[key]}' and `
        str += name
    }
    let deltetSql = 'delete from thumbs_up ' + str.slice(0, -4)
    await new Promise((resolve, reject) => {
        return db.query(deltetSql, (err, data) => {
            if (err) throw err;
            console.log(data)
            resolve(data)//扔出去一个数组
        })
    })
    ctx.body='删除成功'
})
module.exports=thumb